// 获取时间戳
import dayjs from "dayjs";
import {nanoid} from "nanoid";
import Cookies from 'js-cookie'
import store from "@/store";

export const getTimestamp = () => {
    return new Date().getTime()
}
export const updateCookie = (cookie) => {
    localStorage.setItem('cookie', cookie)
}
/**
 * 将给定的数组划分为指定行和列
 * @param row   行数
 * @param column    列数
 * @param arr   原数组
 * @return {*[]}    格式化后的数组
 */
export const formatArray = (row, column, arr) => {
    let tmpArr = [...arr]
    let remainArr = []
    let newRow = row
    if (arr.length < row * column) {
        newRow = Math.floor(arr.length / column)
        const remain = arr.length - newRow * column
        tmpArr = [...arr.slice(0, newRow * column)]
        if (remain) {
            remainArr = [...arr.slice(newRow * column, arr.length)]
        }
    }
    const result = []
    let l = 0, r = l + column
    for (let i = 0; i < newRow; i++) {
        const rowList = tmpArr.slice(l, r)
        // for (let j = 0; j < column; j++) {
        //     const index = Math.floor(Math.random() * tmpArr.length)
        //     rowList.push(tmpArr[index])
        //     tmpArr.splice(index, 1)
        // }
        result.push({
            id: nanoid(),
            data: rowList
        })
        // 更新左右索引
        l = r
        r = l + column
    }
    if (remainArr.length) {
        result.push({
            id: nanoid(),
            data: remainArr
        })
    }
    return result
}
/**
 * 根据时间戳获取时间
 * @param timestamp 时间戳
 * @return {string} dayjs格式时间
 */
export const timestampToTime = (timestamp) => {
    return dayjs(Number.parseInt(timestamp)).format('YYYY年MM月DD日')
}
/**
 * 根据时间戳获取年份
 * @param timestamp
 * @return {string}
 */
export const timeStampToYear = timestamp => {
    return dayjs(Number.parseInt(timestamp)).format('YYYY')
}
/**
 * 将音乐秒数转为时间
 * @param second    时间
 * @param type  类型s/ms
 * @return {`${number}:${*}`}
 */
export const formatMusicTime = (second, type) => {
    const duration = dayjs.duration(second, type)
    return `${duration.minutes()}:${(duration.seconds() < 10 ? '0' : '') + duration.seconds()}`
}

/**
 * 将数字格式化为带有单位的
 * @param num   数字
 * @return {*|string}   格式化后的数字
 */
export const formatBigNum = num => {
    if (num === undefined) {
        return ''
    }
    const digit = 2
    if (num < 10000) {
        return num
    } else if (num < 100000000) {
        const tmp = num / 10000
        return `${tmp.toFixed(digit)}万`
    } else {
        const tmp = num / 100000000
        return `${tmp.toFixed(digit)}亿`
    }
}

/**
 * 从当前播放列表中按顺序选择一个歌曲
 * @param curMusic
 * @param musicList
 * @param flag  表示是下一首1还是上一首-1
 * @return {{}|*}
 */
export const sequentialChooseMusic = (curMusic, musicList, flag) => {
    const {id} = curMusic
    const {playList} = musicList
    let nextIndex = 0
    if (playList.length) {
        playList.forEach((item, index) => {
            if (String(item.id) === String(id)) {
                nextIndex = index + flag
                if (nextIndex < 0) {
                    nextIndex = playList.length - 1
                } else {
                    // 取余防止数组越界
                    nextIndex = (index + flag) % playList.length
                }
            }
        })
        return playList[nextIndex]
    } else {
        return {}
    }
}

/**
 * 打乱数组
 * @param arr
 * @return {*}
 */
export const shuffle = (arr) => {
    const len = arr.length;
    for (let i = len - 1; i >= 0; i--) {
        let randomIndex = Math.floor(Math.random() * (i + 1));
        [arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]];
    }
    return arr;
}

/**
 * 随机选择一个音乐播放
 * @param curMusic  正在播放的音乐
 * @param musicList 播放列表
 * @return {*}  选择的结果
 */
export const randomChooseMusic = (curMusic, musicList) => {
    const {id} = curMusic
    const {playList} = musicList
    let index = Math.floor(Math.random() * playList.length)
    let chooseMusic = playList[index]
    while (String(chooseMusic.id) === String(id)) {
        index = Math.floor(Math.random() * playList.length)
        chooseMusic = playList[index]
    }
    return chooseMusic
}

/**
 * 根据数组的某个属性进行自定义排序（升序）
 * @param arr   数组
 * @param property  属性
 * @returns {*} 排序后的数组
 */
export const orderArrayByAttr = (arr, property) => {
    arr.sort((a, b) => {
        return a[property] < b[property] ? -1 : 1
    })
    return arr
}

// 存储cookie
export const setCookie = data => {
    const cookies = data.split(';;')
    cookies.map(cookie => {
        document.cookie = cookie;
        const cookieKeyValue = cookie.split(';')[0].split('=');
        localStorage.setItem(`cookie-${cookieKeyValue[0]}`, cookieKeyValue[1]);
    });
}

// 获取cookie
export function getCookie(key) {
    return Cookies.get(key) ?? localStorage.getItem(`cookie-${key}`);
}

// 移除cookie
export function removeCookie(key) {
    Cookies.remove(key);
    localStorage.removeItem(`cookie-${key}`);
}

// MUSIC_U 只有在账户登录的情况下才有
export function isLoggedIn() {
    return getCookie('MUSIC_U') !== undefined && getCookie('MUSIC_U') !== null;
}

// 判断是否登录
export const isLogin = () => {
    const {userProfile} = store.state
    return isLoggedIn() && userProfile
}